package config

import (
	"fmt"
	"voice_chat_room/internal/model"
	"voice_chat_room/pkg/logger"
	"voice_chat_room/pkg/passwd"

	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func InitDB() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=%v&loc=%s",
		Config.DB.User,
		Config.DB.Password,
		Config.DB.Host,
		Config.DB.Port,
		Config.DB.DBName,
		Config.DB.Charset,
		Config.DB.ParseTime,
		Config.DB.Loc,
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		logger.Logger.Fatal("Failed to connect to database", zap.Error(err))
	}
	DB = db
	// 自动迁移数据库表
	DB.AutoMigrate(&model.User{})

	initAdminUser()
}

// 初始化管理员用户
func initAdminUser() {
	// 检查管理员用户是否已存在
	var count int64
	DB.Model(&model.User{}).Where("role = ?", "admin").Count(&count)
	if count > 0 {
		logger.Logger.Info("Admin user already exists")
		return
	}
	password := "123456"
	passwordHash, err := passwd.EncryptPassword(password)
	if err != nil {
		logger.Logger.Fatal("Failed to encrypt admin password", zap.Error(err))
	}
	admin := model.User{
		Name:     "admin",
		Email:    "admin@example.com",
		Password: passwordHash, // 密码请加密存储
		Role:     "admin",
	}

	if err := DB.Create(&admin).Error; err != nil {
		logger.Logger.Fatal("Failed to create admin user", zap.Error(err))
	}
}
